package com.lx.service.impl;

import com.lx.entity.User;
import com.lx.repository.UserRepository;
import com.lx.service.UserService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * user服务实现类
 * @author 段誉
 * @create 2019-05-15 15:00
 */
@Service
public class UserServiceImpl implements UserService {
  @Autowired
  private UserRepository userRepository;
  /**
   * 查询所有用户
   *
   * @return java.lang.Object
   * @author 段誉
   * @date 2019/5/15 15:14
   * @since 1.0.0
   */
  @Override
  public List<User> getAll() {
    System.out.println("------------------UserServiceImpl");
    return userRepository.findAll();
  }

  /**
   * 添加用户
   *
   * @return boolean
   * @author 段誉
   * @date 2019/5/15 17:07
   * @since 1.0.0
   */
  @Override
  public void add(User user) {
    userRepository.saveAndFlush(user);
  }

  /**
   * 根据名字进行模糊查询
   *
   * @return java.util.List<com.lx.entity.User>
   * @author 段誉
   * @date 2019/5/20 14:16
   * @since 1.0.0
   */
  @Override
  public List<User> getListByName(String name) {

    return userRepository.findByNameLike(name);
  }

  /**
   * 分页查询
   *
   * @return org.springframework.data.domain.Page<com.lx.entity.User>
   * @author 段誉
   * @date 2019/5/20 15:20
   * @since 1.0.0
   */
  @Override
  public Page<User> getListPageByName(String name, Integer pageNum, Integer pageSize) {
//    单字段排序
//    Sort sort = new Sort(Sort.Direction.ASC, "id");
//    多字段排序
    Sort.Order order1 = new Sort.Order(Sort.Direction.ASC, "tid");
    Sort.Order order2 = new Sort.Order(Sort.Direction.DESC, "name");
    List<Sort.Order> orders = new ArrayList<>();
    orders.add(order1);
    orders.add(order2);
    Sort sort = Sort.by(orders);

    Pageable pageable = PageRequest.of(pageNum, pageSize, sort);
    return userRepository.findPageByNameLike(name, pageable);
  }

  /**
   * 根据用户名查询用户
   *
   * @return com.lx.entity.User
   * @author 段誉
   * @date 2019/5/21 9:37
   * @since 1.0.0
   */
  @Override
  public User getUserInfoByUsername(String username) {
    return userRepository.findOneByUsername(username);
  }
}
